initEditor = ->
  $editor = $('#editor')
  if $editor.length
    $editor.css(minHeight: $(document.body).height())
    editor = new Editor(editable: $editor, toolbar: '#toolkit')

    $('#toolkit .save').bind 'click', (e) ->
      e.preventDefault()
      content = editor.editable.html()
      title = editor.editable.find('h1:first').text()
      if !!title
        href = $(this).find('a')[0].href
        $.post(href, article: {title: title, content_field: content})
      else
        ui.dialog('找不到标题').effect('scale').closable().show().hide(10000)

    $('#toolkit .update').bind 'click', (e) ->
      e.preventDefault()
      content = editor.editable.html()
      title = editor.editable.find('h1:first').text()
      if !!title
        href = $(this).find('a')[0].href
        $.post(href, article: {title: title, content_field: content}, _method: 'PUT')
      else
        ui.dialog('找不到标题').effect('scale').closable().show().hide(10000)

    $('#toolkit .readonly').bind 'click', (e) ->
      e.preventDefault()
      $this = $(this)
      radyOnly = $this.find('i').hasClass('fa-eye');
      editor.setReadonly(radyOnly);
      if radyOnly
        $this.find('i').removeClass().addClass('fa fa-eye-slash')
      else
        $this.find('i').removeClass().addClass('fa fa-eye')


    $('#toolkit .upload').bind 'click', (e) ->
      e.preventDefault()
      new window.UploadModal($('#upload-modal'))
      .onSelect ->
          $img = $(this).closest('.image-selector').find('img')
          editor.formator.exec "insertImage", $img.data('big')
      .show()




    ############################
    ## 代码处理
    ############################


    # 工具栏高亮按钮逻辑
    editor.formator.highlight = ->
      $('code').each (i, dom) ->
        $code = $(dom)
        text = $code.text()
        # 检测 /**language*/ 或者 #language,中间不能有空格
        md = text.match(/^(?=\/\*\*(\w*)\*\/|#(\w+))/)
        if md?
          lang = md[1] || md[2]
          if lang?
            $code.replaceWith(hljs.highlight(lang, text).value)
          else
            $code.replaceWith(hljs.highlightAuto(text).value)


$ ->
  initEditor()
  $(document).on('page:load',initEditor)

  # Index
  $(document).on 'click', '.category-dropdown a', (e) ->
    e.preventDefault()
    $this = $(this)
    categoryId = $this.data('categoryid')
    articleId  = $this.closest('ul').data('articleid')
    $.post("/backend/articles/#{articleId}/set_category", category_id: categoryId, _method: 'patch')


  # 工具栏 fixed
  toolkit = null

  setOnscroll = ->
    window.onscroll = ->
      if window.pageYOffset >= 62
        toolkit.css(position: 'fixed', top: 0)
      else
        toolkit.css(position: 'static', top: 0)

  $(document).on 'page:load', do ->
    toolkit = $('#toolkit----wrap')
    if toolkit.length then setOnscroll() else window.onscroll = null
    arguments.callee
